/**
 * 迭代，[0,1,4,5]，保存1，先把0的next指向4，再将1的next指向5，最后将4的next指向1
 * 其实只要第一步不把4的next指向1就可以，总体思路：保证转换的时候有next可循
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function (head) {
    if (head === null || head.next === null) return head
    // 创建哑结点开头
    let resHead = new ListNode(0), resTail = resHead
    resTail.next = head

    while (resTail.next && resTail.next.next) {
        // 我的思路，两两交换，保存中间节点
        const temp = resTail.next
        resTail.next = resTail.next.next
        temp.next = temp.next.next
        resTail.next.next = temp

        // 指针后移至下个需要交换节点的前一个节点
        resTail = resTail.next.next
    }
    return resHead.next
};


/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs2 = function (head) {
    if (head === null || head.next === null) return head
    let resHead = new ListNode(0), resTail = resHead
    resTail.next = head

    while (resTail.next && resTail.next.next) {
        const node1 = resTail.next
        const node2 = resTail.next.next
        resTail.next = node2
        node1.next = node2.next
        node2.next = node1

        resTail = resTail.next.next
    }
    return resHead.next
};

function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}

let l1 = new ListNode(1)
l1.next = new ListNode(4)
l1.next.next = new ListNode(5)

// console.log(swapPairs(l1))
